package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.repair.mapper.RepairMapper;
import cn.tedu.ivos.repair.pojo.dto.RepairQuery;
import cn.tedu.ivos.repair.pojo.vo.RepairVO;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;

    @Autowired
    RepairMapper repairMapper;



    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询业务，参数:{}",vehicleQuery);
        List<VehicleVO> list=vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        log.debug("保存业务:{}",vehicleSaveParam);
        Vehicle vehicle=new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam,vehicle);
        if (vehicleSaveParam.getId()==null){
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");
            vehicle.setGeofenceBindStatus("0");//车辆初始时不绑定围栏
            vehicleMapper.saveVehicle(vehicle);
        }else {
            vehicle.setUpdateTime(new Date());
            vehicleMapper.updateVehicle(vehicle);

        }
    }

    @Override
    public void deleteVehicleById(Long id) {
        log.debug("删除业务，参数：{}",id);
        vehicleMapper.deleteVehicleById(id);
        RepairQuery repairQuery=new RepairQuery();
        repairQuery.setVehicleId(id);
        List< RepairVO> list =repairMapper.select(repairQuery);
        Long repairId=list.get(0).getId();
        repairMapper.delete(repairId);

    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("解除绑定围栏业务，参数{}",vehicleId);
        Vehicle vehicle=new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.unbindVehicle(vehicle);
    }

    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        log.debug("车辆绑定围栏业务，参数：{}，{}",geofenceId,vehicleId);
        Vehicle vehicle=new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setGeofenceId(geofenceId);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateVehicle(vehicle);
    }
}
